import { log } from 'console';
import { Directive, DirectiveBinding } from 'vue';

const vMove: Directive<any, void> = (el: HTMLElement, binding: DirectiveBinding) => {
    const moveElement: HTMLElement = el as HTMLElement是A组件
    const moveDown = (e: MouseEvent) => {
        var rect = el.getBoundingClientRect()
        var eleft = rect.left; var etop = rect.top
        //获取元素坐标
        console.log(eleft, etop);
        
        var x = e.clientX; var y = e.clientY
        // 按下鼠标时获取鼠标坐标
        // 获取视口的宽度高度
        var lookwidth = document.documentElement.clientWidth
        var lookheight = document.documentElement.clientHeight

        var elementwidth = el.offsetWidth
        var elementheight = el.offsetHeight
        // 不能超过视口，需要计算移动的最大值
        var maxleft = lookwidth - elementwidth
        var maxtop = lookheight - elementheight

        // const X = e.clientX - el.offsetLeft
        // const Y = e.clientY - el.offsetTop
        const move = (e: MouseEvent) => {
            var moveleft = e.clientX - x; 
            var movetop = e.clientY - y
            // 计算移动的距离  移动的距离加上最开始获取元素的宽高
            var left = moveleft + eleft
            var top = movetop + etop


            left = left < 0 ? 0 : left
            left = left > maxleft ? maxleft : left
            top = top < 0 ? 0 : top
            top = top > maxtop ? maxtop : top
            el.style.left = left + 'px'
            el.style.top = top + 'px'
            // if () { }
            // el.style.left = e.clientX - X + 'px'
            // el.style.top = e.clientY - Y + 'px'
        }
        document.addEventListener('mousemove', move)
        document.addEventListener('mouseup', () => {
            document.removeEventListener('mousemove', move)
        })
    }
    moveElement.addEventListener('mousedown', moveDown)

};

export default vMove;